#!/bin/bash

MySQL_user='user'
MySQL_host='127.0.0.1'
MySQL_password='password'
MySQL_port=3306
MySQL_database='database'
MySQL_output_file=/tmp  # 导出位置
MySQL_SqlInfo_file='/root/1_sql_info.txt'  # 查询 SQL 写入此文件


Sqlinfo=$(egrep -v '^$' ${MySQL_SqlInfo_file})

Table_name=$(echo ${Sqlinfo} |sed -En 's/\s*select.*from\s+(`?[a-zA-Z0-9_]+`?\.)?`?([a-zA-Z0-9_]+)`?.*/\2/Ip')

mysql -u${MySQL_user} -p${MySQL_password} -h${MySQL_host} -P${MySQL_port}  -e "use ${MySQL_database}; ${Sqlinfo}" > ${MySQL_output_file}/${Table_name}_$(date '+%Y%m%d%H%M%S').xls

if [[ $? -eq 0 ]];then
    echo "${Table_name} 表导出完成, 保存在 ${MySQL_output_file} 目录下"
else
    echo "${Table_name} 表导出失败"
fi
